package com.rd.student.ruanjian.class3.gaochenxi.day0724;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//使用condition.await()方法+lock的方式
public class third {

   static ReentrantLock lock = new ReentrantLock();
   private static Condition A = lock.newCondition();//Condition是被绑定到Lock上的，必须使用lock.newCondition()才能创建一个Condition
   private static Condition B = lock.newCondition();
   private static Condition C = lock.newCondition();
   private static int num = 0;

   public static void main(String[] args) {
      new At().start();
      new Bt().start();
      new Ct().start();
   }

   static class At extends Thread {
      @Override
      public void run() {
         try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
               while (num % 3 != 0) {
                  A.await();
               }
               System.out.print("A");
               num++;
               B.signalAll();
            }
         } catch (InterruptedException e) {
            throw new RuntimeException(e);
         } finally {
            lock.unlock();
         }
      }
   }

   static class Bt extends Thread {
      @Override
      public void run() {
         try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
               while (num % 3 != 1) {
                  B.await();
               }
               System.out.print("B");
               num++;
               C.signalAll();
            }
         } catch (InterruptedException e) {
            throw new RuntimeException(e);
         } finally {
            lock.unlock();
         }
      }
   }

   static class Ct extends Thread {
      @Override
      public void run() {
         try {
            lock.lock();
            for (int i = 0; i < 10; i++) {
               while (num % 3 != 2) {
                  C.await();
               }
               System.out.print("C");
               num++;
               A.signalAll();
            }
         } catch (InterruptedException e) {
            throw new RuntimeException(e);
         } finally {
            lock.unlock();
         }
      }
   }
}

